package com.cj.common.utils;

import com.cj.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.UUID;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/7/9 23:53
 */
@Slf4j
public class StrUtil {

    /**
     * 32位UUID
     * @return
     */
    public static String getUuid32() {
        return String.valueOf(UUID.randomUUID()).replace("-", "");
    }

    /**
     * 获取ip
     * @return
     */
    public static String getLocalIp() {
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface nif = netInterfaces.nextElement();
                Enumeration<InetAddress> InetAddress = nif.getInetAddresses();
                while (InetAddress.hasMoreElements()) {
                    String ip = InetAddress.nextElement().getHostAddress();
                    if (ip.startsWith("192.168")) {
                        return ip;
                    }
                }
            }
        } catch (SocketException e) {
            log.error(e.getMessage());
            throw new BaseException(e.getMessage());
        }

        return "127.0.0.1";
    }
}
